<template>
  <div>
    <div class="editor" ref="editor" :style="styles"></div>
    <el-upload
      :action="uploadUrl"
      :headers="uploadHeaders"
      accept="image/*"
      :show-file-list="false"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <el-button v-no-more-click size="small" type="primary" v-show="false" :class="uploadBtn">
        点击上传
      </el-button>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { Quill } from '@vueup/vue-quill';
import { getToken } from '@/utils/auth';
import { ElMessage } from 'element-plus';

// 定义 props 与 emit
const props = defineProps({
  value: { type: String, default: '' },
  height: { type: Number, default: null },
  minHeight: { type: Number, default: null },
  qidx: { type: Number, default: 0 },
});
const emit = defineEmits(['input', 'on-change', 'on-text-change', 'on-selection-change', 'on-editor-change']);

// 工具函数（请根据实际情况实现）
function getBaseUrl() {
  // 返回你的基础 URL
  return '';
}
function msgError(message) {
  ElMessage.error(message);
}

// 响应式状态与引用
const editor = ref(null);
const quill = ref(null);
const currentValue = ref(props.value ?? '');

// 上传配置
const uploadUrl = ref(getBaseUrl() + '/common/upload');
const fileList = ref([]);
const uploadHeaders = {
  Authorization: 'Bearer ' + getToken(),
};

// 计算属性：样式和上传按钮的 class
const styles = computed(() => {
  const style = {};
  if (props.minHeight) style.minHeight = `${props.minHeight}px`;
  if (props.height) style.height = `${props.height}px`;
  return style;
});
const uploadBtn = computed(() => 'uploadBtn' + props.qidx);

// Quill 配置项
const options = {
  theme: 'snow',
  bounds: document.body,
  debug: 'warn',
  modules: {
    clipboard: { matchVisual: false },
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ align: [] }],
        ['clean'],
        ['image'],
      ],
      handlers: {
        image: (value) => {
          if (value) {
            console.log('==自定义图片===', value);
            const btn = document.querySelector('.uploadBtn' + props.qidx);
            if (btn) btn.click();
          } else {
            if (quill.value) {
              quill.value.format('image', false);
            }
          }
        },
      },
    },
  },
  placeholder: '请输入内容',
  readOnly: false,
};

// 监听外部 value 变化
watch(
  () => props.value,
  (val) => {
    if (val !== currentValue.value) {
      currentValue.value = val === null ? '' : val;
      if (quill.value) {
        quill.value.clipboard.dangerouslyPasteHTML(currentValue.value);
      }
    }
  },
  { immediate: true }
);

// 初始化编辑器
function init() {
  if (editor.value) {
    quill.value = new Quill(editor.value, options);
    quill.value.clipboard.dangerouslyPasteHTML(currentValue.value);
    quill.value.on('text-change', (delta, oldDelta, source) => {
      const html = editor.value.children[0].innerHTML;
      const text = quill.value.getText();
      currentValue.value = html;
      emit('input', html);
      emit('on-change', { html, text, quill: quill.value });
    });
    quill.value.on('text-change', (delta, oldDelta, source) => {
      emit('on-text-change', delta, oldDelta, source);
    });
    quill.value.on('selection-change', (range, oldRange, source) => {
      emit('on-selection-change', range, oldRange, source);
    });
    quill.value.on('editor-change', (eventName, ...args) => {
      emit('on-editor-change', eventName, ...args);
    });
  }
}

onMounted(() => {
  init();
});
onBeforeUnmount(() => {
  quill.value = null;
});

// 上传成功处理函数
function handleSuccess(response, file, fileListArg) {
  const url = response.fileName;
  if (url && quill.value) {
    const selection = quill.value.getSelection();
    const index = selection ? selection.index : quill.value.getLength();
    quill.value.insertEmbed(index, 'image', getBaseUrl() + url);
    quill.value.setSelection(index + 1);
  } else {
    msgError('图片插入失败');
  }
}

// 上传错误处理函数
function handleError(err, file, fileListArg) {
  msgError('上传图片失败');
}
</script>

<style>
.editor,
.ql-toolbar {
  white-space: pre-wrap !important;
  line-height: normal !important;
}
.quill-img {
  display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}
.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}
.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}
.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>
